package com.cy.mycomposedemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Check
import androidx.compose.material3.MaterialTheme

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

enum class CounterStateEnum {
    NotStarted, InProgress, Completed
}

class MainActivity2 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainScreen()
        }
    }
}

fun showToast(message: String, context: ComponentActivity) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}

suspend fun fetchIconFromNetwork(counterState: CounterStateEnum): ImageVector {
    // Simulate network delay
    delay(200)
    when (counterState) {
        CounterStateEnum.NotStarted -> return Icons.Filled.PlayArrow
        CounterStateEnum.InProgress -> return Icons.Filled.Face
        CounterStateEnum.Completed -> return Icons.Outlined.Check
    }

}


@Composable
fun DisplayNetworkIcon(counterStateEnum: CounterStateEnum) {
//    val _context = LocalContext.current

    //不使用produceState
    // State to hold the current icon
    var icon by remember { mutableStateOf<ImageVector?>(null) }
    // LaunchedEffect to handle asynchronous icon fetching
    LaunchedEffect(counterStateEnum) {
        withContext(Dispatchers.Default){
            // Fetch the icon based on the current counterState
            icon = fetchIconFromNetwork(counterStateEnum)
        }
    }

    //使用produceState
    // Use produceState to manage asynchronous fetching of the icon
    val iconState = produceState<ImageVector?>(initialValue = null, counterStateEnum) {
        withContext(Dispatchers.Default){
            value = fetchIconFromNetwork(counterStateEnum)
        }
    }

    // Display the icon if available, otherwise show a progress indicator
    Box(modifier = Modifier
        .width(40.dp)
        .height(40.dp), contentAlignment = Alignment.Center) {
        iconState.value?.let { icon ->
            Icon(imageVector = icon, contentDescription = "Network fetched icon",
                modifier = Modifier.size(48.dp))
        } ?: CircularProgressIndicator()
    }
}

suspend fun startCounter(
    increment: () -> Unit,
    onCounterEnded: () -> Unit
) {
    Log.i("Counter", "Starting Counter")
    delay(2000) // Use delay from kotlinx.coroutines
    for (i in 1..10) {
        delay(1000) // Use delay from kotlinx.coroutines
        increment()
    }
    onCounterEnded()
}

@Composable
fun MainScreen() {

    val context = LocalContext.current as ComponentActivity

    var counter by remember {
        mutableStateOf(0)
    }

    var counterState by remember {
        mutableStateOf(CounterStateEnum.NotStarted)
    }

    var counterMessage by remember {
        mutableStateOf("Counter not yet started")
    }

    SideEffect {
        when (counter) {
            0 -> {
                counterState = CounterStateEnum.NotStarted
            }
            10 -> {
                counterState = CounterStateEnum.Completed
            }
            else -> {
                counterState = CounterStateEnum.InProgress
            }
        }
        Log.i("Counter SideEffect", "Counter State $counterState")
    }

    DisposableEffect(key1 = Unit){
        Log.i("mycy", "DisposableEffect")
        onDispose {
            Log.i("mycy", "DisposableEffect Disposed")
        }
    }

    val counterBackGroundColor by remember(counter) {
        derivedStateOf {
            if (counter % 2 == 0) Color.Green else Color.Red
        }
    }

    var increaseCounter = {
        counter++
        counterMessage = "Counter Increased to $counter"
    }

    Log.i("Counter", " Counter value $counter")

    Surface(
        //Aligns the content of this component along the specified [alignment] lines.
        color = MaterialTheme.colorScheme.background,
        modifier = Modifier.fillMaxSize(),
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier
                .fillMaxSize(1f)
                .padding(1.dp)
        ) {

            CounterMessage(counterMessage,
                context = context,
                increaseCounter = increaseCounter)

            DisplayNetworkIcon(counterState)


            Row(
                verticalAlignment = Alignment.CenterVertically,

                ) {

                Text(
                    text = "$counter", modifier = Modifier
                        .padding(20.dp)
                        .background(counterBackGroundColor)
                        .width(50.dp)
                        .height(50.dp),
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                    fontSize = 35.sp
                )
            }

        }

    }
}

@Composable
fun CounterMessage(counterMessage: String, context: ComponentActivity, increaseCounter: () -> Unit) {
    val counterMessageLatest by rememberUpdatedState(counterMessage)
    Log.i("Counter", " Rendering CounterMessage with $counterMessageLatest")
    LaunchedEffect(key1 = Unit) {
        Log.i("Counter", " LaunchedEffect with $counterMessageLatest")
        startCounter({ increaseCounter() }){
            Log.i("Counter", "Counter Ended with $counterMessageLatest")
            showToast("Counter Ended", context)
        }
    }
    Text(
        text = counterMessageLatest,
        fontSize = 20.sp,
        modifier = Modifier.padding(20.dp)
    )
}



@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MainScreen()
}
